class Watcher {
  constructor (opts) {
    this.$data = this.getType(opts.data) === 'Object' ? opts.data : {}
    this.$watch = this.getType(opts.watch) === 'Object' ? opts.watch : {}
    for (let key in this.$data) {
      this.setData(key)
    }
  }

  getType (target) {
    return Object.prototype.toString.call(target).slice(8, -1)
  }

  setData (_key) {
    Object.defineProperty(this, _key, {
      get: function () {
        return this.$data[_key]
      },

      set: function (val) {
        const oldVal = this.$data[_key]
        if (oldVal === val) return val
        this.$data[_key] = val
        if (this.$watch[_key] && 'function' === typeof this.$watch[_key]) {
          this.$watch[_key].call(this, val, oldVal)
        }
        return val
      }
    })
  }
}

let vm = new Watcher({
    data:{
        a: 0,
        b: 'hello'
    },
    watch:{
        a (newVal,oldVal) {
          console.log(`我被改变啦！，现在是 ${ newVal }`)
        }
    }
})

// console.log(vm.a)
// console.log(vm.b)
vm.a = 100
console.log(vm.a)
